/*
   Copyright 2009 Bloo. All Rights Reserved.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package org.youtensils.www.client.data.youtube;

import java.util.ArrayList;

import org.youtensils.www.client.data.JsonLoader;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;

/**
 * Wrapper for the YouTube GData API.
 * @author Bobby Soares
 */
public class YouTubeLoader extends JsonLoader {
	private ArrayList<YouTubeDataListener> listeners;
	/**
	 * The default constructor.
	 */
	public YouTubeLoader(){
		this.listeners = new ArrayList<YouTubeDataListener>();
	}
	/**
	 * Performs a video search against YouTube.
	 * @param query the text to search for
	 * @param category the category to which the search should be restricted
	 * @param author the author to which the search should be restricted
	 * @param orderBy the sort order that the search results should follow
	 * @param safeSearch whether the search should be restricted to unflagged videos
	 * @param startIndex the index starting at which results should be returned
	 * @param maxResults the maximum amount of search results to return
	 */
	public void searchVideos(String query, String category, String author,
			YouTubeSearchSortBy orderBy, YouTubeSearchFilter safeSearch,
			int startIndex, int maxResults){
		try{
			String url = "http://gdata.youtube.com/feeds/api/videos?" +
					"q=" + query +
					(author != null && author != "" ? "&author=" + author : "") +
					(category != null && category != "" ? "&category=" + category : "") +
					"&orderby=" + orderBy.toString() +
					"&start-index=" + startIndex +
					"&max-results=" + maxResults +
					"&v=2&alt=json-in-script&format=5&callback=";
			this.getJson(url, this);
		}catch(Exception x){}
	}
	/**
	 * Adds a YouTube event listener.
	 * @param listener the YouTube event listener to add
	 */
	public void addListener(YouTubeDataListener listener){
		this.listeners.add(listener);
	}
	public void handleJsonResponse(JavaScriptObject jso) {
		if(listeners != null){
			YouTubeSearchResults res = new YouTubeSearchResults();
			if(jso != null) res = YouTubeSearchResults.fromFeed(new JSONObject(jso));
			for(int i=0; i<this.listeners.size(); i++){
				this.listeners.get(i).onSearchResults(res);
			}
		}
	}
}
